/*
    Priscilla - A library for enocean network access
    Copyright (C) 2012-2013 B. Aigner / R. Wagner

    This program is free software; you can redistribute it and/or 
    modify it under the terms of the GNU General Public License 
    as published by the Free Software Foundation; either version 2 
    of the License, or at your option any later version. 
 
    This program is distributed in the hope that it will be useful, 
    but WITHOUT ANY WARRANTY; without even the implied warranty of 
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
    GNU General Public License for more details. 
 
    You should have received a copy of the GNU General Public License 
    along with this program; if not, write to the Free Software 
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA. 
 
    Linking this library statically or dynamically with other modules is 
    making a combined work based on this library. Thus, the terms and 
    conditions of the GNU General Public License cover the whole 
    combination. 
 
    As a special exception, the copyright holders of this library give you 
    permission to link this library with independent modules to produce an 
    executable, regardless of the license terms of these independent 
    modules, and to copy and distribute the resulting executable under terms 
    of your choice, provided that you also meet, for each linked independent 
    module, the terms and conditions of the license of that module. An 
    independent module is a module which is not derived from or based on 
    this library. If you modify this library, you may extend this exception 
    to your version of the library, but you are not obligated to do so. If 
    you do not wish to do so, delete this exception statement from your 
    version. 
*/

package at.technikum_wien.embsys.aat.PriscillaCore.connection;

import java.io.BufferedReader;
import org.apache.log4j.Logger;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.InterruptedIOException;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.util.List;

import javax.xml.parsers.ParserConfigurationException;


import org.apache.log4j.Logger;
import org.xml.sax.SAXException;

import at.technikum_wien.embsys.aat.PriscillaCore.component.EnoceanComponent;
import at.technikum_wien.embsys.aat.PriscillaCore.data.EnoceanRawData;
import at.technikum_wien.embsys.aat.PriscillaCore.enums.TeachInOptions;
import at.technikum_wien.embsys.aat.PriscillaCore.exception.EnOceanExceptionConnection;
import at.technikum_wien.embsys.aat.PriscillaCore.link.EnOceanLinkImpl;
import at.technikum_wien.embsys.aat.PriscillaCore.parsing.EnoceanComponentParser;


/**
 * Data receiver thread
 * 
 * This thread is started by the TCP socket connector and is responsible 
 * for receiving raw frames through the socket.
 * After a frame is received, it will be parsed
 * 
 * @author R. Wagner
 */
public final class IPGatewayDataReceiver extends Thread {

	private Socket socket;
	private List<?> listeners;
//	private char[] dataArray;
	private TeachInOptions options = null;
	private static final Logger log = Logger.getLogger(IPGatewayDataReceiver.class);

	IPGatewayDataReceiver(Socket socket, List<?> listeners) {
		super("EnoceanNet/IP receiver");
		this.socket = socket;
		this.listeners = listeners;
		setDaemon(true); // set Deamon Threat
		log.debug("IP receiver thread started");
	}
	
	IPGatewayDataReceiver(Socket socket, List<?> listeners, TeachInOptions options) {
		super("EnoceanNet/IP receiver");
		this.socket = socket;
		this.options = options;
		this.listeners = listeners;
		setDaemon(true); // set Deamon Threat
		log.debug("IP receiver thread started");
	}
	
	/* (non-Javadoc)
	 * @see java.lang.Thread#run()
	 */
	public void run() {
		@SuppressWarnings("unused")
		BufferedReader inputReader = null;
		InputStreamReader inputStreamReader = null;
		EnoceanComponentParser parser = new EnoceanComponentParser(listeners, options);

		try {
			inputReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			inputStreamReader = new InputStreamReader(socket.getInputStream());
			
			char[] charBuf = new char[28];
			
			for (;;) {
				// reader for socket
				charBuf = checkInputStream(inputStreamReader);
				
				if (charBuf != null) {
					log.debug("IP character telegram received");
					EnoceanRawData data = new EnoceanRawData();
					data.setEnoceanData(charBuf);
				
					@SuppressWarnings("unused")
					EnoceanComponent enoceanComponent = parser.parseEnoceanData(data);
				}
			}
		} catch (final InterruptedIOException e) {
			log.error("IP thread exception: " + e.getMessage());
		} catch (final IOException e) {
			log.error("IP thread exception: " + e.getMessage());
		} catch (ParserConfigurationException e) {
			log.error("IP thread exception: " + e.getMessage());
		} catch (SAXException e) {
			log.error("IP thread exception: " + e.getMessage());
		}
	}
	
/**
 * Check for the sync header and shift the buffer corresponding
 * 
 * This method checks for the sync header and shifts the data
 * to put this header to the beginning of the message. Otherwise
 * the following parsing will throw exceptions because of wrong data
 * 
 * @param inputStreamReader
 * @return Character array with the corrected raw data
 */
char[] checkInputStream(InputStreamReader inputStreamReader) {
	
	try {
		
		boolean enoceanPackageReceived = false;
		int bufferCounter = 0;
		char[] charBuf = new char[100];
		char[] charReturn = new char[28];
		String stringBuf = "";
		
		while (!enoceanPackageReceived) {
			
			int data = inputStreamReader.read();
			
			charBuf[bufferCounter++] = (char) data;
			if(bufferCounter == 100) return null;
			
			stringBuf = String.valueOf(charBuf);
			
			int syncMsgReceived = stringBuf.indexOf("A55A");
			
			if (syncMsgReceived != -1) {
				if (bufferCounter >= syncMsgReceived + 28) {
					int j = 0;
					for (int i = syncMsgReceived; i < bufferCounter; i++) {
						charReturn[j++] = charBuf[i];
					}
					return charReturn;
				}
			}
		}

	} catch (IOException e) {
		log.error("IP thread exception: " + e.getMessage());
	} catch (ArrayIndexOutOfBoundsException e) {
		log.error("IP thread exception: " + e.getMessage());
	}
	return null;

	
}
	
	
}
